<?php
namespace backend\components;

use Yii;
use yii\helpers\ArrayHelper;
use backend\components\Utools;
use backend\modules\admin\models\ReleasePoint;
use backend\modules\admin\models\Site;
use backend\components\Ftp;
use backend\modules\content\models\Category;
use backend\components\Urls;
use backend\modules\admin\models\Urlrule;
/**
 * @author libin
 * @time 2011 8 23
 * @for 栏目页更新自动同步
 * 
 * *********************使用方式************************
 * 
 * 		$durl=new Urls();
 *      $html=new Whtml();       
 *      $data=(new Content())->get_one('id=13');//获取单条新闻数据
 *      $fileurl=$durl->show($data['id'], $page = 0, $data['catid']);//利用url类生成新闻url
 *      $html->show($fileurl[1],$data);//生成新闻页静态并发布
 *      $html->category(130,1);//生成栏目id为130 的 页码为1 的栏目页
 * 
 * 
*/
class Whtml{

	public $siteid=1;
	public $categorys=array();
	public function __construct() {
		$this->siteid = Utools:: get_siteid();
		$this->site = Site::findOne($this->siteid);
		$this->html_root = 'html';//如果不生成到根目录，默认的html生成目录
		$categorys=Category::find()->where(array('siteid'=>$this->siteid,'status'=>0))->asArray()->all();
        $categorysT = [];
		foreach($categorys as $cat)
		{
			$categorysT[$cat['catid']]=$cat;
		}
		$this->categorys=$categorysT;
		$sites=Site::find()->where(array('status'=>0))->asArray()->all();
		foreach($sites as $site)
		{
			$sitesT[$site['siteid']]=$site;
		}
		$this->sitelist=$sitesT;
		$urlrules = Urlrule::find()->where(array('status'=>0))->asArray()->all();//查出所有的urlrule中的数据
		foreach($urlrules as $url)
		{
			$urlrulesT[$url['urlruleid']]=$url;   //使key键值和urlruleid相对应，是一样的
		}
		$this->urlrules=$urlrulesT;
	}

	
	/**
	 * 生成内容页
	 * @param  $file 文件地址
	 * @param  $data 数据
	 * @param  $array_merge 是否合并
	 * @param  $action 方法
	 * @param  $upgrade 是否是升级数据
	 */
	public function show($file, $data = '', $array_merge = 1,$action = 'add',$upgrade = 0) {

	
		if($upgrade) $file = '/'.ltrim($file,WEB_PATH);
		$allow_visitor = 1;
		$id = $data['id'];
		$temp=$data;
	
	
		
		//$data['username']=$temp['username'];
		//通过rs获取原始值
		$rs = $data;
		if(isset($data['paginationtype'])) {
			$paginationtype = $data['paginationtype'];
			$maxcharperpage = $data['maxcharperpage'];
		} else {
			$paginationtype = 0;
		}
		$catid = $data['catid'];		
		$CATEGORYS = $this->categorys;
		//print_r($data);
		$CAT = $CATEGORYS[$catid];
		$CAT['setting'] = Utools::string2array($CAT['setting']);
		

		//最顶级栏目ID
		//$arrparentid = explode(',', $CAT['arrparentid']);
		//$top_parentid = $arrparentid[1] ? $arrparentid[1] : $catid;

		//$file = '/'.$file;
		//添加到发布点队列
		//当站点为非系统站点


		
		$tempfile=$file;
		//echo 'tempfile:--'.$tempfile;
		//echo '------';
	//	$this->queue->add_queue($action,$file,$this->siteid);

		$modelid = $CAT['modelid'];
		
		//$this->db = pc_base::load_model('content_model');
		//$this->db->set_model($modelid);
		extract($data);
		
		$title = strip_tags($title);
		//SEO
		$seo_keywords = '';
		//if(!empty($keywords)) $seo_keywords = implode(',',$keywords);
		$siteid = $this->siteid;
		//$SEO = seo($siteid, $catid, $title, $description, $seo_keywords);
		
		$ishtml = 1;
		$template = $CAT['template_show'];
		$template=$template?$template:'show';
		//分页处理
		$pages = $titles = '';
		
		//分页处理结束		
		$htmlfile = CACHE_PATH.DIRECTORY_SEPARATOR.'HTML'.DIRECTORY_SEPARATOR.$this->siteid.DIRECTORY_SEPARATOR.$file;
		
		/**生成PC**/
		ob_start();
		include  Utools::template('content', $template);
		$this->createhtml($htmlfile);
		/** added by libin for 自动同步**/
		
		$ftps = new Ftp();
		$this->site = Site::findOne($this->siteid);
		$this->point = ReleasePoint::findOne($this->site->release_point);
		$release_point=$this->point;
		
		
		//$release_point = $release->get_one(array('id'=>$this->point[0]));
		if ($ftps->connect($release_point['host'], $release_point['username'], $release_point['password'], $release_point['port'], $release_point['pasv'], $release_point['ssl'])) {

			
			if ($release_point['path'])
			{
				$ftps->chdir($release_point['path']);
			}

			//echo $release_point['path'].$file.'<br>';
			//echo $htmlfile.'<br>';
			//$file=$tempfile;
			//$file = $site_dir.$file;
			if ($ftps->put($release_point['path'].$file, $htmlfile)) {
				$status = 1;
				
			}
		
							
		}
		else
		{
			die('发布点设置错误');
		}
		//die('ddd');

	

	}

	/**
	 * 生成栏目列表
	 * @param $catid 栏目id
	 * @param $page 当前页数
	 */
	public function category($catid, $page = 0) {
		$CAT = $this->categorys[$catid];
		@extract($CAT);
		if(!$ishtml) return $url;
		if(!$catid) exit('栏目id不存在');
		$CATEGORYS = $this->categorys;
		if(!isset($CATEGORYS[$catid])) exit('栏目不存在');
		$siteid = $CAT['siteid'];
		$copyjs = '';
		
		
		$page = intval($page);
		$urlmodel=new Urls();
		$parentdir = $urlmodel->get_categorydir($catid);//获取父栏目目录
		//$parentdir = $CAT['parentdir'];
		$catdir = $CAT['catdir'];
		//检查是否生成到根目录
		$create_to_html_root = $CAT['creat_to_html_root'];
		//$base_file = $parentdir.$catdir.'/';
		//生成地址
		if($CAT['creat_to_html_root']) $parentdir = '';
		
		if(!empty($CAT['parentid']))
		{
			$parentcat=$CATEGORYS[$CAT['parentid']];//获取父栏目                                             此处如果父栏目id为0，怎么办？
			//获取父级的配置，看是否生成静态，如果是动态则直接把父级目录调过来为生成静态目录所用
			//$parent_setting = string2array($CATEGORYS[$CAT['parentid']]['setting']);
			if($parentcat['ishtml']==0 && $CAT['ishtml']==1){
				$parentdir = $CATEGORYS[$CAT['parentid']]['catdir'].'/';
			}
		}
		
		$base_file = $urlmodel->get_list_url($CAT['category_ruleid'],$parentdir, $catdir, $catid, $page);
		
		
		$obase_file=$base_file;//保存栏目相对目录路径，用以发布点发布
		//$base_file = '/'.$base_file;
		
		$root_domain = preg_match('/^((http|https):\/\/)([a-z0-9\-\.]+)\/$/',$CAT['url']) ? 1 : 0;//是否绑定二级域名或者动态地址
		$htm_prefix = $root_domain ? '' : $this->html_root;
		
		
		//判断二级域名是否直接绑定到该栏目
		$root_domain = preg_match('/^((http|https):\/\/)([a-z0-9\-\.]+)\/$/',$CAT['url']) ? 1 : 0;
		$count_number = substr_count($CAT['url'], '/');
		$urlrules = $this->urlrules;
		$urlrules = explode('|',$urlrules[$category_ruleid]['urlrule']);
		
		if($create_to_html_root) {
			if($this->siteid==1) {
				$file =  CACHE_PATH.DIRECTORY_SEPARATOR.'HTML'.DIRECTORY_SEPARATOR.$this->siteid.DIRECTORY_SEPARATOR.$base_file;
			} else {
				$file = CACHE_PATH.DIRECTORY_SEPARATOR.'HTML'.DIRECTORY_SEPARATOR.$this->siteid.DIRECTORY_SEPARATOR.$base_file;
			}
			
			foreach ($urlrules as $_k=>$_v) {
				$urlrules[$_k] = '/'.$_v;
			}
		} else {
			$file = CACHE_PATH.DIRECTORY_SEPARATOR.'HTML'.DIRECTORY_SEPARATOR.$this->siteid.DIRECTORY_SEPARATOR.$this->html_root.DIRECTORY_SEPARATOR.$base_file;
			$second_domain = 0;//判断该栏目是否绑定了二级域名或者上级栏目绑定了二级域名，存在的话，重新构造列表页url规则
			foreach ($urlrules as $_k=>$_v) {
					$urlrules[$_k] = $htm_prefix.'/'.$_v;
			}
		}

		
		if($type==0 || $type==1) {
			$template = $CAT['template_category'] ? $CAT['template_category'] : 'category';
			$template_list = $CAT['template_list'] ? $CAT['template_list'] : 'list';
			$template = $child ? $template : $template_list;
			$arrparentid = explode(',', $arrparentid);
			$top_parentid = isset($arrparentid[1]) ? $arrparentid[1] : $catid;
			$array_child = array();
			$self_array = explode(',', $arrchildid);
			foreach ($self_array as $arr) {
				if($arr!=$catid) $array_child[] = $arr;
			}
			$arrchildid = implode(',', $array_child);
			//URL规则
			$urlrules = implode('~', $urlrules);
			
			!defined('URLRULE')?define('URLRULE',$urlrules):'';
			
			
			$GLOBALS['URL_ARRAY'] = array('categorydir'=>$parentdir, 'catdir'=>$catdir, 'catid'=>$catid);
		} else {
		//单网页
			$datas = $this->page($catid);
			if($datas) extract($datas);
			$template = $setting['page_template'] ? $setting['page_template'] : 'page';
			$parentid = $CATEGORYS[$catid]['parentid'];
			$arrchild_arr = $CATEGORYS[$parentid]['arrchildid'];
			if($arrchild_arr=='') $arrchild_arr = $CATEGORYS[$catid]['arrchildid'];
			$arrchild_arr = explode(',',$arrchild_arr);
			array_shift($arrchild_arr);
			$keywords = $keywords ? $keywords : $setting['meta_keywords'];
			$SEO = seo($siteid, 0, $title,$setting['meta_description'],$keywords);
		}
	
		ob_start();
		include  Utools::template('content',$template);
		$this->createhtml($file);
		$ftps = new Ftp();
		$this->site = Site::findOne($this->siteid);
		$this->point = ReleasePoint::findOne($this->site->release_point);
		$release_point=$this->point;
		//$release_point = $release->get_one(array('id'=>$this->point[0]));
		
		if ($ftps->connect($release_point['host'], $release_point['username'], $release_point['password'], $release_point['port'], $release_point['pasv'], $release_point['ssl'])) {

			//var_dump($release_point);
			//echo $obase_file.'<br>';
			//echo $file;
			if ($release_point['path'])
			{
				$ftps->chdir($release_point['path']);
			}

			//echo $release_point['path'].$file;
			//$file=$tempfile;
			//$file = $site_dir.$file;
			//echo $obase_file;
			if ($ftps->put($release_point['path'].$obase_file, $file)) {
				$status = 1;
				
			}
		}
		else
		{
			die('发布点设置错误');
		}
	}
	/**
	 * 更新首页
	 */
	public function index() {
		$file =  CACHE_PATH.DIRECTORY_SEPARATOR.'HTML'.DIRECTORY_SEPARATOR.$this->siteid.DIRECTORY_SEPARATOR.'index.html';
		//$SEO = seo($this->siteid);
		$siteid = $this->siteid;
		$CATEGORYS = $this->categorys;
		//$style = $this->sitelist[$siteid]['default_style'];
		ob_start();
		include Utools::template('content','index');
		return $this->createhtml($file, 1);
		$ftps = new Ftp();
		$this->point = ReleasePoint::findOne($this->site->release_point);
		$release_point=$this->point;
		//$release_point = $release->get_one(array('id'=>$this->point[0]));
		if ($ftps->connect($release_point['host'], $release_point['username'], $release_point['password'], $release_point['port'], $release_point['pasv'], $release_point['ssl'])) {

			
			if ($release_point['path'])
			{
				$ftps->chdir($release_point['path']);
			}

			//echo $release_point['path'].$file;
			//$file=$tempfile;
			//$file = $site_dir.$file;
			//echo $obase_file;
			if ($ftps->put($release_point['path'].'index.html', $file)) {
				$status = 1;
				
			}
		
							
		}
		else
		{
			die('发布点设置错误');
		}
	}	


	/**
	 * 写入文件
	 * @param $file 文件路径
	 * @param $copyjs 是否复制js，跨站调用评论时，需要该js
	 */
	protected function createhtml($file, $copyjs = '') {

		$data = ob_get_contents();
		ob_clean();
		$dir = dirname($file);
		if(!is_dir($dir)) {
		 	mkdir($dir, 0777,1);
		}
		
		$strlen = file_put_contents($file, $data);
	
	
		return $strlen;
	}

}
